package com.bbt.dormassistant.service.impl;

import com.bbt.dormassistant.dao.MessageMapper;
import com.bbt.dormassistant.entity.Message;
import com.bbt.dormassistant.entity.MessageTitle;
import com.bbt.dormassistant.service.MessageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class MessageServiceImpl implements MessageService {

    @Value("${imageFilePath}")
    private String imageFilesPath;


    @Resource
    private MessageMapper messageMapper;


    /**
     *
     * @param userId 用户ID
     * @return  List<Message>
     */
    @Override
    public List<Message> getAllMessageByUserId(String userId) {
        return messageMapper.selectAllByUserId(userId);
    }


    /**
     *
     * @return List<Message>
     */
    @Override
    public List<Message> getAllMessage() {

        return messageMapper.selectAll();
    }


    /**
     *
     * @param currIndex 当前页
     * @param pageSize 页大小
     * @return List<MessageTitle>
     */
    @Override
    public List<MessageTitle> getAllMessageTitles(Integer currIndex,Integer pageSize) {
        Map<String,Object> data = new HashMap<>();
        data.put("currIndex",currIndex==null? 0:(currIndex-1)*pageSize );
        data.put("pageSize",pageSize==null? 100:pageSize);
        return messageMapper.selectAllTitles(data);
    }


    /**
     *
     * @param userId  用户ID
     * @param title 标题
     * @param text 内容
     * @return Boolean
     */
    @Override
    public Boolean addMessage(String userId, String title, String text) {
        try{
            Message message = new Message();
            int messageId = (int)System.currentTimeMillis();
            message.setMessageId(messageId);

            message.setUserId(userId);
            message.setTittle(title);
            message.setText(text);
            message.setTime(new Date());


            return messageMapper.insert(message) == 1 ;

        }catch (Exception e ){
            e.printStackTrace();
            return false;
        }
    }

    /**
     *
     * @param messageId 消息的ID
     * @return Message
     */
    @Override
    public Message getMessageByMessageId(Integer messageId) {
        return messageMapper.selectByPrimaryKey(messageId);
    }

    @Override
    public String addImage(MultipartFile image) throws IOException {
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + image.getOriginalFilename();
        String destFileName = imageFilesPath + File.separator + fileName;
        File destFile = new File(destFileName);
        image.transferTo(destFile);
        String imageUrl="http://129.204.20.87/images/" + fileName;
        return imageUrl;
    }


}
